package com.zhenyi.jiahua.index.admin;

import java.io.File;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;

import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jiahua.common.model.JhArrange;
import com.jiahua.common.model.JhArrangeStudent;
import com.jiahua.common.model.JhCourse;
import com.jiahua.common.model.JhSchool;
import com.jiahua.common.model.JhStaff;
import com.jiahua.common.model.JhStudent;
import com.utils.DateUtils;
import com.utils.PathUtils;
import com.zhenyi.jiahua.index.JHController;
import com.zhenyi.jiahua.task.JHOnCourseTask;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.ReUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

/**
 * 排课
 * 
 * @author cen
 *
 */
public class ArrangeController extends JHController {
	private final Integer CANCEL_TIME = PropKit.getInt("CANCEL_TIME", 3600);
	private final Integer JOIN_TIME = PropKit.getInt("JOIN_TIME", 3600);

	private void renderArrageFile(List<Record> records) {
		ArrayList<Map<String, Object>> arrayList = new ArrayList<>();
		for (Record record : records) {
			String date = DateUtil.format(record.get("startTime"), "yyyy-MM-dd");
			String time = DateUtil.format(record.get("startTime"), "HH:mm") + "~"
					+ DateUtil.format(record.get("endTime"), "HH:mm");
			Map<String, Object> row = new LinkedHashMap<>();
			row.put("日期", date);
			row.put("星期", date);
			row.put("时间", time);
			row.put("课程名称", record.getStr("name"));
			row.put("主题", record.getStr("topic"));
			row.put("老师", record.getStr("teacherEnglishName"));
			row.put("已选/总数", record.getInt("joinCount") + "/" + record.getInt("limit"));
			row.put("校区", record.getStr("schoolName"));
			row.put("教室", record.getStr("classroom"));
			arrayList.add(row);
		}
		String name = "排课.xlsx";
		String path = PathUtils.getFile("jh", "temp", "excel", name);
		ExcelWriter writer = ExcelUtil.getWriter(path);
		// 合并单元格后的标题行，使用默认标题样式
		// writer.merge(4, "一班成绩单");
		// 一次性写出内容，使用默认样式
		writer.write(arrayList);
		// 关闭writer，释放内存
		writer.close();
		File file = new File(path);
		renderFile(file);
	}

	public void list() {
		String startDate = getPara("startDate", DateUtil.today() + " 00:00:00");
		String endDate = getPara("endDate", DateUtil.today() + " 23:59:59");
		Long schoolId = getParaToLong("schoolId");
		Long staffId = getParaToLong("staffId");
		Long courseId = getParaToLong("courseId");
		String tag = getPara("tag");

		/**
		 * 是否有人选的课
		 */
		Integer joinCourse = getParaToInt("joinCourse");
		Kv kv = Kv.create();
		if (schoolId != null) {
			setAttr("schoolId", schoolId);
			kv.set("schoolId", schoolId);
		}
		if (staffId != null) {
			setAttr("staffId", staffId);
			kv.set("staffId", staffId);
		}
		if (courseId != null) {
			setAttr("courseId", courseId);
			kv.set("courseId", courseId);
		}
		if (tag != null) {
			setAttr("tag", tag);
			kv.set("tag", tag);
		}
		if (joinCourse != null) {
			setAttr("joinCourse", joinCourse);
			kv.set("joinCourse", joinCourse);
		}
		kv.set("startTime", startDate);
		kv.set("endTime", endDate);

		Integer dl = getParaToInt("dl", 0);
		if (dl.equals(1)) {
			List<Record> records = JhArrange.dao.getArranges(null, startDate, endDate, kv);
			renderArrageFile(records);
			return;
		}
		Page<Record> pages = JhArrange.dao.getArranges(null, startDate, endDate, kv, getPage(), PAGE_SIZE);
		for (Record record : pages.getList()) {
			if (record.get("startTime") != null) {
				record.set("date", DateUtil.format(record.get("startTime"), "yyyy-MM-dd"));
				record.set("time", DateUtil.format(record.get("startTime"), "HH:mm") + "~"
						+ DateUtil.format(record.get("endTime"), "HH:mm"));
			}
		}

		SqlPara sqlParaCourseTime = Db.use("jiahua").getSqlPara("JHArrangeListCourseTime", kv);
		Record timeRecord = Db.use("jiahua").findFirst(sqlParaCourseTime);
		setAttr("courseTime", 0);
		if (timeRecord != null) {
			BigDecimal val = timeRecord.getBigDecimal("courseTime");
			if (val != null) {
				setAttr("courseTime", val.intValue());
			}
		}
		setRainbow(pages);
		setItems(jsonObject(pages.getList()));
		setAttr("startDate", startDate);
		setAttr("endDate", endDate);
		setAttr("schools", jsonObject(JhSchool.dao.findAll()));
		SqlPara teacherPara = Db.use("jiahua").getSqlPara("JHFindCourseTeachers");
		List<JhStaff> staffs = JhStaff.dao.find(teacherPara);
		setAttr("staffs", jsonObject(staffs));
		SqlPara coursePara = Db.use("jiahua").getSqlPara("JHFindAvaliableCourse");
		List<JhCourse> courses = JhCourse.dao.find(coursePara);
		setAttr("courses", jsonObject(courses));
		String tags = PropKit.get("JH_COURSE_TAGS");
		setAttr("tags", tags);
		render("/jh/admin/arrange/index.html");
	}

	/**
	 * 任课老师课程列表
	 */
	public void teacherCourseList() {
		Long staffId = getParaToLong("staffId");
		JhStaff teacher = JhStaff.dao.findById(staffId);
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		Kv kv = Kv.create();
		Page<Record> pages = JhArrange.dao.getArranges(teacher, startDate, endDate, kv, getPage(), PAGE_SIZE);

		setAttr("courseTime", JhArrange.dao.getCourseTotalTime(kv));

		setRainbow(pages);
		setItems(pages.getList());
		render("");
	}

	/**
	 * 当前登录老师的排课
	 */
	public void arranges() {
		JhStaff teacher = getStaff();
		String startDate = getPara("startDate", DateUtil.today() + " 00:00:00");
		String endDate = getPara("endDate", DateUtil.today() + " 23:59:59");
		/**
		 * 是否有人选的课
		 */
		Integer joinCourse = getParaToInt("joinCourse");
		Long schoolId = getParaToLong("schoolId");
		Long staffId = getParaToLong("staffId");
		Long courseId = getParaToLong("courseId");
		String tag = getPara("tag");

		Kv kv = Kv.create();
		if (teacher != null) {
			kv.set("staffId", teacher.getId());
		}

		if (schoolId != null) {
			setAttr("schoolId", schoolId);
			kv.set("schoolId", schoolId);
		}
		if (staffId != null) {
			setAttr("staffId", staffId);
			kv.set("staffId", staffId);
		}
		if (courseId != null) {
			setAttr("courseId", courseId);
			kv.set("courseId", courseId);
		}
		if (tag != null) {
			setAttr("tag", tag);
			kv.set("tag", tag);
		}
		if (joinCourse != null) {
			setAttr("joinCourse", joinCourse);
			kv.set("joinCourse", joinCourse);
		}
		kv.set("startTime", startDate);
		kv.set("endTime", endDate);

		Page<Record> pages = JhArrange.dao.getArranges(teacher, startDate, endDate, kv, getPage(), PAGE_SIZE);
		for (Record record : pages.getList()) {
			if (record.get("startTime") != null) {
				record.set("date", DateUtil.format(record.get("startTime"), "yyyy-MM-dd"));
				record.set("time", DateUtil.format(record.get("startTime"), "HH:mm") + "~"
						+ DateUtil.format(record.get("endTime"), "HH:mm"));
			}
		}
		setAttr("courseTime", JhArrange.dao.getCourseTotalTime(kv));
		setRainbow(pages);
		setItems(jsonObject(pages.getList()));
		setAttr("startDate", startDate);
		setAttr("endDate", endDate);

		setAttr("schools", jsonObject(JhSchool.dao.findAll()));
		SqlPara coursePara = Db.use("jiahua").getSqlPara("JHFindAvaliableCourse");
		List<JhCourse> courses = JhCourse.dao.find(coursePara);
		setAttr("courses", jsonObject(courses));
		String tags = PropKit.get("JH_COURSE_TAGS");
		setAttr("tags", tags);

		SqlPara sqlParaCourseTime = Db.use("jiahua").getSqlPara("JHArrangeListCourseTime", kv);
		Record timeRecord = Db.use("jiahua").findFirst(sqlParaCourseTime);
		setAttr("courseTime", 0);
		if (timeRecord != null) {
			BigDecimal val = timeRecord.getBigDecimal("courseTime");
			if (val != null) {
				setAttr("courseTime", val.intValue());
			}
		}

		render("/jh/admin/arrange/myArrange.html");
	}

	public void info() {
		List<JhSchool> schools = JhSchool.dao.findAll();
		setAttr("schools", jsonObject(schools));
		SqlPara coursePara = Db.use("jiahua").getSqlPara("JHFindAvaliableCourse");
		List<JhCourse> courses = JhCourse.dao.find(coursePara);
		setAttr("courses", ReUtil.escape(JsonKit.toJson(courses)));
		SqlPara teacherPara = Db.use("jiahua").getSqlPara("JHFindCourseTeachers");
		List<JhStaff> staffs = JhStaff.dao.find(teacherPara);
		setAttr("staffs", ReUtil.escape(JsonKit.toJson(staffs)));
		// setAttr("partTimeTeacher", JhStaff.dao.getPartTimeTeacher());
		Long arrangeId = getParaToLong("arrangeId");
		JhArrange arrange;
		if (arrangeId == null) {
			arrange = new JhArrange();
		} else {
			arrange = JhArrange.dao.findById(arrangeId);
		}
		if (arrange.getStartTime() != null) {
			arrange.put("date", DateUtil.format(arrange.getStartTime(), "yyyy-MM-dd"));
			arrange.set("startTime", DateUtil.format(arrange.getStartTime(), "HH:mm"));
			arrange.set("endTime", DateUtil.format(arrange.getEndTime(), "HH:mm"));
		}
		setInfoItem(arrange);
		render("/jh/admin/arrange/info.html");
	}

	/**
	 * 排课
	 */
	@Override
	public void submit() {
		JhStaff staff = getStaff();
		Long arrangeId = getParaToLong("arrangeId");
		Long courseId = getParaToLong("courseId");
		if (courseId == null) {
			renderFailure("请选择课程");
			return;
		}
		Long staffId = getParaToLong("staffId");
		String date = getPara("date");
		if (StrKit.isBlank(date)) {
			renderFailure("请选择日期");
			return;
		}
		String startTime = getPara("startTime", "09:00");
		Date start = DateUtils.dateFromString(date + " " + startTime, DateUtils.YYYYMMDD_HHMM);
		Integer courseTime = getParaToInt("courseTime", 60);
		Date end = new DateTime(start).plusMinutes(courseTime).toDate();
		if (staffId != null) {

			Kv kv = Kv.create();
			kv.set("staffId", staffId);
			kv.set("startTime", DateUtil.format(start, "yyyy-MM-dd HH:mm:ss"));
			kv.set("endTime", DateUtil.format(end, "yyyy-MM-dd HH:mm:ss"));
			SqlPara sqlPara = Db.use("jiahua").getSqlPara("JHCheckArrangeTime", kv);
			List<JhArrange> arranges = JhArrange.dao.find(sqlPara);
			for (JhArrange arrange : arranges) {
				if (arrangeId != null && arrange.getId().equals(arrangeId)) {
					continue;
				}
				String message = "该时间段与课程：{} - {} ({}~{}) 冲突";
				message = StrFormatter.format(message, arrange.get("courseName"), arrange.getTopic(),
						DateUtil.format(arrange.getStartTime(), "yyyy-MM-dd HH:mm"),
						DateUtil.format(arrange.getEndTime(), "HH:mm"));
				renderFailure(message);
				return;
			}
		}
		Long schoolId = getParaToLong("schoolId");
		JhArrange arrange;
		if (arrangeId == null) {
			arrange = new JhArrange();
			arrange.setSchoolId(staff.getSchoolId());
			arrange.setCourseId(courseId);
			arrange.save();
		} else {
			arrange = JhArrange.dao.findById(arrangeId);
			arrange.setCourseId(courseId);
		}
		if (schoolId != null) {
			arrange.setSchoolId(schoolId);
		}
		String topic = getPara("topic");
		topic = topic.replace("'", "`");
		// String endTime = getPara("endTime");
		Integer limit = getParaToInt("limit", 0);
		String partTimeTeacherName = getPara("partTimeTeacherName");
		String classroom = getPara("classroom");
		Integer isHide = getParaToInt("isHide", 0);
		arrange.setTopic(topic);
		arrange.setStartTime(start);
		// arrange.setEndTime(DateUtils.dateFromString(date + " " + endTime,
		// DateUtils.YYYYMMDD_HHMM));
		arrange.setEndTime(end);
		arrange.setCourseTime(courseTime);
		arrange.setLimit(limit);
		arrange.setStaffId(staffId);
		// arrange.setTeacherName(teacherName);
		arrange.setPartTimeTeacherName(partTimeTeacherName);
		arrange.setClassroom(classroom);
		arrange.setIsHide(isHide);
		arrange.update();
		renderSuccess();
	}

	/**
	 * 新增排课页面
	 */
	public void addArrange() {
		List<JhSchool> schools = JhSchool.dao.findAll();
		setAttr("schools", jsonObject(schools));
		SqlPara coursePara = Db.use("jiahua").getSqlPara("JHFindAvaliableCourse");
		List<JhCourse> courses = JhCourse.dao.find(coursePara);
		setAttr("courses", ReUtil.escape(JsonKit.toJson(courses)));
		SqlPara teacherPara = Db.use("jiahua").getSqlPara("JHFindCourseTeachers");
		List<JhStaff> staffs = JhStaff.dao.find(teacherPara);
		setAttr("staffs", ReUtil.escape(JsonKit.toJson(staffs)));
		String tags = PropKit.get("JH_COURSE_TAGS");
		setAttr("tags", tags);

		JhArrange arrange = new JhArrange();
		setInfoItem(arrange);

		render("/jh/admin/arrange/addArrange.html");
	}

	/**
	 * 新增排课（多个主题）
	 */
	public void submitWithMultiTopics() {
		renderFailure("保存失败");
		JhStaff staff = getStaff();
		Long courseId = getParaToLong("courseId");
		if (courseId == null) {
			renderFailure("请选择课程");
			return;
		}
		String topicsJson = getPara("topicsJson");
		// Long staffId = getParaToLong("staffId");
		// String partTimeTeacherName = getPara("partTimeTeacherName");
		String classroom = getPara("classroom");
		Long schoolId = getParaToLong("schoolId");
		Integer limit = getParaToInt("limit", 0);
		Integer isHide = getParaToInt("isHide", 0);
		String studentIds = getPara("studentIds", ",");
		String[] studentIdList = studentIds.split(",");
		boolean ignoreConflict = getParaToInt("ignoreConflict") != null && getParaToInt("ignoreConflict") == 1;

		JSONArray topics = JSONUtil.parseArray(topicsJson);
		boolean flag = Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				for (int i = 0; i < topics.size(); i++) {
					JSONObject topic = topics.getJSONObject(i);
					String topicName = topic.getStr("name");
					String date = topic.getStr("date");
					String startTime = topic.getStr("startTime");
					Integer courseTime = topic.getInt("courseTime");
					Integer type = topic.getInt("type");
					Long staffId = null;
					if (type.equals(0)) {
						staffId = topic.getLong("staffId");
					}
					Date start = DateUtils.dateFromString(date + " " + startTime, DateUtils.YYYYMMDD_HHMM);
					Date end = new DateTime(start).plusMinutes(courseTime).toDate();

					if (!ignoreConflict && staffId != null) {
						Kv kv = Kv.create();
						kv.set("staffId", staffId);
						kv.set("startTime", DateUtil.format(start, "yyyy-MM-dd HH:mm:ss"));
						kv.set("endTime", DateUtil.format(end, "yyyy-MM-dd HH:mm:ss"));
						SqlPara sqlPara = Db.use("jiahua").getSqlPara("JHCheckArrangeTime", kv);
						List<JhArrange> arranges = JhArrange.dao.find(sqlPara);
						for (JhArrange arrange : arranges) {
							arrange.print();
							String message = "{} 的时间段与课程：{} - {} ({}~{}) 冲突，是否强制提交？";
							message = StrFormatter.format(message, topicName, arrange.get("courseName"),
									arrange.getTopic(), DateUtil.format(arrange.getStartTime(), "yyyy-MM-dd HH:mm"),
									DateUtil.format(arrange.getEndTime(), "HH:mm"));
							renderFailure(message);
							return false;
						}
					}
					JhArrange arrange = new JhArrange();
					if (schoolId != null) {
						arrange.setSchoolId(schoolId);
					} else {
						arrange.setSchoolId(staff.getSchoolId());
					}
					if (type.equals(0)) {
						arrange.setStaffId(staffId);
					} else if (type.equals(1)) {
						String partTimeTeacherName = topic.getStr("partTimeTeacherName");
						arrange.setPartTimeTeacherName(partTimeTeacherName);
					}
					arrange.setCourseId(courseId);
					arrange.setTopic(topicName);
					arrange.setStartTime(start);
					// arrange.setEndTime(DateUtils.dateFromString(date + " " +
					// endTime,
					// DateUtils.YYYYMMDD_HHMM));
					arrange.setEndTime(end);
					arrange.setCourseTime(courseTime);
					arrange.setLimit(limit);
					arrange.setStaffId(staffId);
					// arrange.setTeacherName(teacherName);
					// arrange.setPartTimeTeacherName(partTimeTeacherName);
					arrange.setClassroom(classroom);
					arrange.setIsHide(isHide);
					if (!arrange.save()) {
						return false;
					}
					Long arrangeId = arrange.getId();
					for (String studentId : studentIdList) {
						JhArrangeStudent arrangeStudent = new JhArrangeStudent();
						arrangeStudent.setArrangeId(arrangeId);
						arrangeStudent.setStudentId(Long.parseLong(studentId));
						arrangeStudent.setStatus(JhArrangeStudent.STATUS_JOIN);
						arrangeStudent.setType(JhArrangeStudent.TYPE_TEACHER_SELECT);
						if (!arrangeStudent.save()) {
							return false;
						}
					}
				}
				return true;
			}
		});
		if (flag) {
			renderSuccess();
		}
	}

	/**
	 * 删除排课
	 */
	@Override
	public void delete() {
		Long arrangeId = getParaToLong("arrangeId");
		JhArrange arrange = JhArrange.dao.findById(arrangeId);
		arrange.setFlag(1);
		arrange.update();
		renderSuccess();
	}

	/**
	 * 课程添加学生页面
	 */
	public void addStudentToArrange() {
		Long arrangeId = getParaToLong("arrangeId");
		if (arrangeId == null) {
			renderError(404);
			return;
		}
		JhArrange arrange = JhArrange.dao.findById(arrangeId);
		if (arrange == null) {
			LogKit.warn("error arrangeId " + arrangeId);
			renderError(404);
			return;
		}
		arrange.updateJoinCount();
		JhSchool school = JhSchool.dao.findById(arrange.getSchoolId());
		arrange.put("schoolName", school.getName());
		JhCourse course = JhCourse.dao.findById(arrange.getCourseId());
		arrange.put("courseName", course.getName());
		arrange.put("tags", course.getTags());
		if (arrange.getStaffId() != null) {
			JhStaff staff = JhStaff.dao.findById(arrange.getStaffId());
			arrange.put("teacherName", staff.getName());
		}
		if (arrange.getStartTime() != null) {
			arrange.put("date", DateUtil.format(arrange.getStartTime(), "yyyy-MM-dd"));
			arrange.set("startTime", DateUtil.format(arrange.getStartTime(), "HH:mm"));
			arrange.set("endTime", DateUtil.format(arrange.getEndTime(), "HH:mm"));
		}
		setInfoItem(arrange);
		String tags = PropKit.get("JH_COURSE_TAGS");
		setAttr("tags", tags);
		render("/jh/admin/arrange/addStudent.html");
		/**
		 * 找到排课选课的所有学生
		 */
		Kv kv = Kv.by("arrangeId", arrangeId);
		// kv.set("status", 1);
		SqlPara sqlPara = Db.use("jiahua").getSqlPara("JHFindArrangeStudents", kv);
		Page<Record> pages = Db.use("jiahua").paginate(getPage(), PAGE_SIZE, sqlPara);
		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));
	}

	// public void students() {
	// Long arrangeId = getParaToLong("arrangeId");
	// if (arrangeId == null) {
	// renderSuccess();
	// return;
	// }
	// Kv kv = Kv.by("arrangeId", arrangeId);
	// kv.set("status", 1);
	// SqlPara sqlPara = Db.use("jiahua").getSqlPara("JHFindArrangeStudents",
	// kv);
	// Page<Record> pages = Db.use("jiahua").paginate(getPage(), PAGE_SIZE,
	// sqlPara);
	// renderSuccess(pages.getList());
	// }

	/**
	 * 课程添加学生
	 */
	public void addStudents() {
		renderSuccess();
		String idString = getPara("ids");
		if (StrKit.isBlank(idString)) {
			return;
		}
		String[] ids = idString.split(",");
		Long arrangeId = getParaToLong("arrangeId");
		if (ids == null) {
			return;
		}
		JhArrange arrange = JhArrange.dao.findById(arrangeId);

		// Date startTime = arrange.getStartTime();
		// Date now = new Date();
		// Long bet = (startTime.getTime() - now.getTime()) / 1000;
		// if (bet <= JOIN_TIME) {
		// renderMsg("很遗憾,已过订课时间");
		// return;
		// }

		boolean isLimitedAddStudent = PropKit.getBoolean("JH_ENABLE_LIMIT_ADD_STUDENT", true);
		if (isLimitedAddStudent) {
			if (arrange.getJoinCount() + ids.length > arrange.getLimit()) {
				renderMsg("选课人数超过限制");
				return;
			}
		}

		String errorStudentName = "";
		for (String studentId : ids) {
			Kv kv = Kv.create();
			kv.set("studentId", studentId);
			kv.set("startTime", arrange.getStartTime());
			kv.set("endTime", arrange.getEndTime());
			SqlPara sameArrangePara = Db.use("jiahua").getSqlPara("JHFindStudentSimeArrangeTime", kv);
			List<Record> items = Db.use("jiahua").find(sameArrangePara);
			if (items.size() > 0) {
				JhStudent student = JhStudent.dao.findById(studentId);
				errorStudentName = errorStudentName + student.getName() + " ";
			}
		}
		if (StrKit.notBlank(errorStudentName)) {
			renderMsg(errorStudentName + "该时段已有选课");
			return;
		}

		for (String studentId : ids) {

			JhArrangeStudent arrangeStudent = JhArrangeStudent.dao.findById(arrangeId, studentId);
			if (arrangeStudent == null) {
				arrangeStudent = new JhArrangeStudent();
				arrangeStudent.setArrangeId(arrangeId);
				arrangeStudent.setStudentId(Long.parseLong(studentId));
				arrangeStudent.setStatus(JhArrangeStudent.STATUS_JOIN);
				arrangeStudent.setType(JhArrangeStudent.TYPE_TEACHER_SELECT);
				arrangeStudent.save();
			} else {
				if (arrangeStudent.getStatus().equals(JhArrangeStudent.STATUS_DONE)) {
					continue;
				}
				arrangeStudent.setStatus(JhArrangeStudent.STATUS_JOIN);
				arrangeStudent.setCancelTime(null);
				arrangeStudent.setType(JhArrangeStudent.TYPE_TEACHER_SELECT);
				arrangeStudent.update();
			}
		}
		arrange.updateJoinCount();
	}

	public void removeStudents() {

		renderSuccess();
		String idString = getPara("ids");
		if (StrKit.isBlank(idString)) {
			return;
		}
		String[] ids = idString.split(",");
		Long arrangeId = getParaToLong("arrangeId");
		if (ids == null) {
			return;
		}
		JhArrange arrange = JhArrange.dao.findById(arrangeId);
		Date startTime = arrange.getStartTime();
		Date now = new Date();
		Long bet = (startTime.getTime() - now.getTime()) / 1000;
		if (bet <= CANCEL_TIME) {
			renderMsg("超过取消时间");
			return;
		}
		for (String studentId : ids) {
			JhArrangeStudent arrangeStudent = JhArrangeStudent.dao.findById(arrangeId, studentId);
			if (arrangeStudent == null) {
			} else {
				arrangeStudent.setStatus(JhArrangeStudent.STATUS_CANCEL);
				arrangeStudent.setCancelTime(new Date());
				arrangeStudent.update();
			}
		}
		arrange.updateJoinCount();
	}

	public void tri() {
		new JHOnCourseTask().run();
		renderSuccess();
	}

	private ArrayList<Map<String, Object>> getEmptyRows(int count) {
		ArrayList<Map<String, Object>> rows = new ArrayList<>();
		for (int i = 0; i < count; i++) {
			Map<String, Object> row = new LinkedHashMap<>();
			row.put("姓名", "");
			row.put("上课", "");
			row.put("课程", "");
			row.put("等级", "");
			row.put("老师", "");
			row.put("教室", "");
			row.put("签到", "");
			rows.add(row);
		}
		return rows;
	}

	public void downloadStudents() {

		String startDate = getStartToday();
		String endDate = getEndToday();
		Kv kv = Kv.create();
		kv.set("startTime", startDate);
		kv.set("endTime", endDate);
		Long schoolId = getParaToLong("schoolId");
		Long staffId = getParaToLong("staffId");
		Long courseId = getParaToLong("courseId");
		String tag = getPara("tag");

		if (schoolId != null) {
			setAttr("schoolId", schoolId);
			kv.set("schoolId", schoolId);
		}

		if (staffId != null) {
			setAttr("staffId", staffId);
			kv.set("staffId", staffId);
		}
		if (courseId != null) {
			setAttr("courseId", courseId);
			kv.set("courseId", courseId);
		}
		if (tag != null) {
			setAttr("tag", tag);
			kv.set("tag", tag);
		}

		SqlPara sqlPara = Db.use("jiahua").getSqlPara("JHOnCourseStudents", kv);
		List<Record> items = Db.use("jiahua").find(sqlPara);

		String name = "签到表" + ".xlsx";
		String path = PathUtils.getFile("jh", "temp", "excel", name);
		ExcelWriter writer = ExcelUtil.getWriter(path);

		ArrayList<Map<String, Object>> rows = new ArrayList<>();
		Long aid = null;
		for (Record record : items) {
			String courseName = record.getStr("name");
			Date startTime = record.getDate("startTime");
			Date endTime = record.getDate("endTime");
			String dt = DateUtil.format(startTime, DateUtils.YYYYMMDD_HHMMSS);
			dt = dt + " ~ " + DateUtil.format(endTime, "HH:mm");
			// String tags = record.getStr("tags").replace(",", " ");
			String studentTag = record.getStr("studentTag");
			String teacherName = record.getStr("teacherName");
			if (StrKit.isBlank(teacherName)) {
				teacherName = "无上课老师";
			}
			String classroom = record.getStr("classroom");
			if (StrKit.isBlank(classroom)) {
				classroom = "";
			}

			Long arrangeId = record.getLong("arrangeId");
			if (!arrangeId.equals(aid)) {
				if (rows.size() > 0) {
					rows.addAll(getEmptyRows(10));
				}
				String title = courseName + " " + teacherName + " " + classroom + " ";
				writer.write(rows);
				writer.merge(6, title);
				rows = new ArrayList<>();
			}
			aid = arrangeId;
			Map<String, Object> row = new LinkedHashMap<>();
			row.put("上课时间:", dt);
			row.put("姓名", record.getStr("studentName"));
			// row.put("课程", courseName);
			row.put("等级", studentTag);
			// row.put("主题", record.getStr("topic"));
			// row.put("老师", teacherName);
			// row.put("教室", classroom);
			row.put("签到", "");
			row.put("迟到", "");
			row.put("旷课", "");
			row.put("备注", record.getStr("mark"));
			rows.add(row);
		}
		rows.addAll(getEmptyRows(10));
		writer.write(rows);
		writer.close();
		File file = new File(path);
		if (!file.exists()) {
			renderError(404);
			return;
		}
		renderFile(file);
	}

	/**
	 * 签到表
	 */
	public void students() {
		String startDate = getStartToday();
		String endDate = getEndToday();

		Long schoolId = getParaToLong("schoolId");
		Long staffId = getParaToLong("staffId");
		Long courseId = getParaToLong("courseId");
		String tag = getPara("tag");

		Kv kv = Kv.create();
		if (schoolId != null) {
			setAttr("schoolId", schoolId);
			kv.set("schoolId", schoolId);
		}
		kv.set("startTime", startDate);
		kv.set("endTime", endDate);

		if (staffId != null) {
			setAttr("staffId", staffId);
			kv.set("staffId", staffId);
		}
		if (courseId != null) {
			setAttr("courseId", courseId);
			kv.set("courseId", courseId);
		}
		if (tag != null) {
			setAttr("tag", tag);
			kv.set("tag", tag);
		}

		setAttr("startTime", startDate);
		setAttr("endTime", endDate);

		setAttr("schools", jsonObject(JhSchool.dao.findAll()));
		SqlPara teacherPara = Db.use("jiahua").getSqlPara("JHFindCourseTeachers");
		List<JhStaff> staffs = JhStaff.dao.find(teacherPara);
		setAttr("staffs", jsonObject(staffs));
		SqlPara coursePara = Db.use("jiahua").getSqlPara("JHFindAvaliableCourse");
		List<JhCourse> courses = JhCourse.dao.find(coursePara);
		setAttr("courses", jsonObject(courses));
		String tags = PropKit.get("JH_COURSE_TAGS");
		setAttr("tags", tags);

		SqlPara sqlPara = Db.use("jiahua").getSqlPara("JHOnCourseStudents", kv);
		Page<Record> pages = Db.use("jiahua").paginate(getPage(), PAGE_SIZE, sqlPara);
		setRainbow(pages);
		setItems(jsonObject(pages.getList()));
		render("/jh/admin/arrange/students.html");
	}

	/**
	 * 保存选课学生备注
	 */
	public void setArrangeStudentMark() {
		Long arrangeId = getParaToLong("arrangeId");
		Long studentId = getParaToLong("studentId");
		String mark = getPara("mark");
		// if (StrKit.isBlank(mark)) {
		// renderMsg("保存失败.");
		// return;
		// }
		JhArrangeStudent arrangeStudent = JhArrangeStudent.dao.findById(arrangeId, studentId);
		if (arrangeStudent == null) {
			renderMsg("保存失败");
			return;
		}
		arrangeStudent.setMark(mark);
		arrangeStudent.update();
		renderMsg("保存成功");
	}
}
